package jchat.genral;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import chat.jdaas.R;

import jchat.imageutil.ImageLoader;
import jchat.interfaces.IAppManager;
import jchat.services.IMService;
import jchat.types.ConversionType;
import jchat.types.FriendInfo;
import jchat.types.MessageInfo;
import jchat.types.MessageStatus;
import jchat.types.Session;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import jchat.Controller.FriendController;
import jchat.Controller.LocalStorageHandler;
import jchat.genral.MessageAdpter;
import android.widget.Toast;
//import chat.jdaas.R;


public class Messaging extends ListActivity implements OnClickListener  {
	  private PopupWindow mpopup;
	private static final int MESSAGE_CANNOT_BE_SENT = 0;
	public String username;
	private EditText messageText;
	private String settingsTAG = "AppNameSettings";
	ConversionType sendtype=new ConversionType();
	private SharedPreferences prefs;
	//private EditText messageHistoryText;
	private ListView messageview;
	public ImageLoader imageLoader; 
	MessageAdpter adpt;
	private Button sendMessageButton,btnOk,btnCancel;
	private static final int Gallery = Menu.FIRST;
	private IAppManager imService;
	private FriendInfo friend = new FriendInfo();
	private LocalStorageHandler localstoragehandler; 
	private Cursor dbCursor;
	Bundle extras;
	String pwd=null;
	String imagepath;
	ImageView imageview;
	TextView friendname;
	private ImageView profilepic;
	 ProgressDialog simpleWaitDialog;
	Users objuser;
private boolean status=false;
Bitmap bitmap;
String msg;
String gettype;
	private ArrayList<Users> messagelist=new ArrayList<Users>();
	private ServiceConnection mConnection = new ServiceConnection() {
      
		
		
		public void onServiceConnected(ComponentName className, IBinder service) {          
            imService = ((IMService.IMBinder)service).getService();
        }
        public void onServiceDisconnected(ComponentName className) {
        	imService = null;
            Toast.makeText(Messaging.this, R.string.local_service_stopped,
                    Toast.LENGTH_SHORT).show();
        }
    };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);	   
		
		setContentView(R.layout.messagess); //messaging_screen);
				
	//	messageHistoryText = (EditText) findViewById(R.id.messageHistory);
		//messageview=(ListView) findViewById(R.id.list);
		messageText = (EditText) findViewById(R.id.message);
		profilepic=(ImageView)findViewById(R.id.userpic);
		friendname=(TextView)findViewById(R.id.friendname);
				
objuser=new Users(this);
imageLoader=new ImageLoader(this);
		messageText.requestFocus();			
		
		sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
		
	     extras = this.getIntent().getExtras();
		
		friend.userKey=extras.getString(FriendInfo.USER_KEY);
		friend.userName = extras.getString(FriendInfo.USERNAME);
		friend.ip = extras.getString(FriendInfo.IP);
		friend.url=extras.getString(FriendInfo.profile_pice);
		friend.port = extras.getString(FriendInfo.PORT);
		msg = extras.getString(MessageInfo.MESSAGETEXT);
	gettype=extras.getString(MessageInfo.MESSAGETYPE);
		prefs = getSharedPreferences(settingsTAG, 0);
		this.pwd=prefs.getString(Session.PASSWORD, "");
		
		setTitle(friend.userName);
		//friend.userName
		friendname.setText(friend.userName);
	ImageView image=profilepic;
	imageLoader.DisplayImage(friend.url, image);
		getdatafromlocal();
	//	EditText friendUserName = (EditText) findViewById(R.id.friendUserName);
	//	friendUserName.setText(friend.userName);
		
		
		
		
		sendMessageButton.setOnClickListener(new OnClickListener(){
			CharSequence message;
			Handler handler = new Handler();
			public void onClick(View arg0) {
				message = messageText.getText();
				if (message.length()>0) 
				{		
				//adpt.notifyDataSetChanged();
					getListView().setSelection(messagelist.size()-1);
					appendToMessageHistory(imService.getUsername(), message.toString(),true,"text");
					
					localstoragehandler.insert(imService.getUsername(), friend.userKey, message.toString(),true,"text");
								
					messageText.setText("");
					Thread thread = new Thread(){	
						String result=null;
						public void run() {
							try {
								
							    result=imService.sendMessage(imService.getUsername(), friend.userKey, message.toString());
								
								
							} catch (UnsupportedEncodingException e) {
								

								e.printStackTrace();
							}
							if (result == null || result.equals(0)) 
							{
								/*
								 * Authenticatin failed, inform the user
								 */
								handler.post(new Runnable(){
									public void run() {	
										Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();

										status=false;
										//showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
									}									
								});
														
							}
							else {
							
								/*
								 * if result not equal to authentication failed,
								 * result is equal to friend list of the user
								 */		
								handler.post(new Runnable(){
									public void run() {		
										//contactlist=imService.sendcontectlist(data);
										
									//	Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_LONG).show();
                              									
								       /* Intent i = new Intent(getApplicationContext(), FriendList.class);
										i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
										
										// Add new Flag to start new Activity
										i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										startActivity(i);
										
										finish();*/
									
									}									
								});
								
							}
						}						
					};
					thread.start();
										
				}
				
			}});
		
		messageText.setOnKeyListener(new OnKeyListener(){
			

			@Override
			public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
				// TODO Auto-generated method stub
				if (arg1 == 66){
					sendMessageButton.performClick();
					return true;
				}
				return false;
			}
			
			
		});
				
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		int message = -1;
		switch (id)
		{
		case MESSAGE_CANNOT_BE_SENT:
			message = R.string.message_cannot_be_sent;
		break;
		}
		
		if (message == -1)
		{
			return null;
		}
		else
		{
			return new AlertDialog.Builder(Messaging.this)       
			.setMessage(message)
			.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					/* User clicked OK so do some stuff */
				}
			})        
			.create();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(messageReceiver);
		unbindService(mConnection);
		
		FriendController.setActiveFriend(null);
		
	}

	@Override
	protected void onResume() 
	{		
		super.onResume();
		//Toast.makeText(getApplicationContext(), "Resume", Toast.LENGTH_LONG).show();
		bindService(new Intent(Messaging.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
	//	appendToMessageHistory(imService.getUsername(), message.toString(),true,"text");
		IntentFilter i = new IntentFilter();
		//appendToMessageHistory(imService.getUsername(), "hellooo",true,"text");
		i.addAction(IMService.TAKE_MESSAGE);
		//this.onCreate(null);
		registerReceiver(messageReceiver, i);
		
		FriendController.setActiveFriend(friend.userKey);	
		
		
		
	}
	/*==========message recevier class==================*/
	public class  MessageReceiver extends BroadcastReceiver {
	
		@Override
		public void onReceive(Context context, Intent intent) 
		{		
			Bundle extra = intent.getExtras();
			String username = extra.getString(MessageInfo.USERID);			
			String message = extra.getString(MessageInfo.MESSAGETEXT);
			String type=extra.getString(MessageInfo.MESSAGETYPE);
			//Boolean side=extra.getBoolean(MessageInfo.side, true);
			if (username != null && message != null)
			{
			if (friend.userKey.equals(username)) {
				if(type.equals("image"))
				{
					/*objuser=new Users(context);
					objuser.seturl(message);
					messagelist.add(objuser);
					adpt=new MessageAdpter(context, messagelist);
					setListAdapter(adpt);*/
					new ImageDownloaderTask().execute(message);
					String iamgemessage=new ImageDownloaderTask().getpath();
					appendToMessageHistory(username, iamgemessage, false, type);
					//appendToMessageHistory(username, message,false);
					localstoragehandler.insert(username,imService.getUsername(), message,false,"image");
				}
				else if(type.equals("text"))
				{
					appendToMessageHistory(username, message,false,"text");
					localstoragehandler.insert(username,imService.getUsername(), message,false,"text");
				}
				}
				else {
					if (message.length() > 15) {
						message = message.substring(0, 15);
					}
					Toast.makeText(Messaging.this,  username + " says '"+
													message + "'",
													Toast.LENGTH_SHORT).show();		
				}
			}			
		}
		
	};
	private MessageReceiver messageReceiver = new MessageReceiver();
	
	public  void appendToMessageHistory(String username, String message,boolean side,String type) {
		try
		{
		if (username != null && message != null) {
			//messagelist.add(str);
			//String type=MessageInfo.MESSAGETYPE;
			messagelist.add(new Users(username, message,side,type,status));
			//ArrayAdapter<String> adpt=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,messagelist);
			//messageview.setAdapter(adpt);
			adpt=new MessageAdpter(this, messagelist);
			
			setListAdapter(adpt);
		      //messageview.setAdapter(adpt);
		}
		}
		catch(Exception e)
		{
			Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
		}
			
		
	}
	
	
	@Override
	protected void onDestroy() {
	    super.onDestroy();
	    if (localstoragehandler != null) {
	    	localstoragehandler.close();
	    }
	    if (dbCursor != null) {
	    	dbCursor.close();
	    }
	}

	
	//@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {		
		boolean result = super.onCreateOptionsMenu(menu);		

		menu.add(0, Gallery, 0, R.string.media);
		return result;
	}
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
	    
		switch(item.getItemId()) 
	    {
	    	case Gallery:
	    		View popUpView = getLayoutInflater().inflate(R.layout.popwindoes, null); // inflating popup layout
                mpopup = new PopupWindow(popUpView, LayoutParams.FILL_PARENT, LayoutParams.MATCH_PARENT, true); //Creation of popup
                mpopup.setAnimationStyle(android.R.style.Animation_Dialog);   
                mpopup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                mpopup.showAtLocation(popUpView, Gravity.FILL_HORIZONTAL, 0, 0);    // Displaying popup
                 btnOk = (Button)popUpView.findViewById(R.id.btnOk);
                 imageview=(ImageView)popUpView.findViewById(R.id.sendimage);
	    		btnOk.setOnClickListener(this);
	          btnCancel = (Button)popUpView.findViewById(R.id.btnCancel);
	    		 btnCancel.setOnClickListener(this);
	    		return true;
	    	
	    }
	       
	    return super.onMenuItemSelected(featureId, item);
	}
/*==============================Show Windows Pop Up for Image sending=======================*/

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnOk:
			mpopup.dismiss();
			  java.text.DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			   //get current date time with Date()
			   Date date = new Date();
			   System.out.println(dateFormat.format(date));
			   String temp_name=dateFormat.format(date);
			storeImage(bitmap, temp_name+".jpg");
			getListView().setSelection(messagelist.size()-1);
			appendToMessageHistory(username, imagepath, true, "image");
			localstoragehandler.insert(imService.getUsername(), friend.userKey, imagepath.toString(),true,"image");
			//this.onCreate(null);
			getdatafromlocal();
			new ImageUploaderTask().execute(imagepath);	
			
			
			break;
		case R.id.btnCancel:
			Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
			Toast.makeText(getApplicationContext(), "cancle", Toast.LENGTH_LONG).show();
			break;
		default:
			break;
		}
		
	}
	/*================================Caught Image========================================*/
	 @Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		    
	    	if (requestCode == 1 && resultCode == RESULT_OK) {
	            //Bitmap photo = (Bitmap) data.getData().getPath(); 
	          
	            Uri selectedImageUri = data.getData();
	            imagepath = getPath(selectedImageUri);
	            final int THUMBSIZE = 64;

	             bitmap = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(imagepath), 
	                                THUMBSIZE, THUMBSIZE);
	            bitmap=BitmapFactory.decodeFile(imagepath);
	            imageview.setImageBitmap(bitmap);
	           // messageText.setText("Uploading file path:" +imagepath);
	            
		    	
		    }
	    }
	    	 public String getPath(Uri uri) {
	    	        String[] projection = { MediaStore.Images.Media.DATA };
	    	        Cursor cursor = managedQuery(uri, projection, null, null, null);
	    	        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    	        cursor.moveToFirst();
	    	        return cursor.getString(column_index);
	    	    }
	    	 
	    	 private String storeImage(Bitmap imageData, String filename) {
	    			//get path to external storage (SD card)
	    			String filePath = null ;
	    			String iconsStoragePath = Environment.getExternalStorageDirectory() + "/myAppDir/myImages/Sent/";
	    			File sdIconStorageDir = new File(iconsStoragePath);

	    			//create storage directories, if they don't exist
	    			sdIconStorageDir.mkdirs();

	    			try {
	    				filePath= sdIconStorageDir.toString() + filename;
	    				FileOutputStream fileOutputStream = new FileOutputStream(filePath);

	    				BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);

	    				//choose another format if PNG doesn't suit you
	    				imageData.compress(CompressFormat.PNG, 100, bos);

	    				bos.flush();
	    				bos.close();

	    			} catch (FileNotFoundException e) {
	    				Log.w("TAG", "Error saving image file: " + e.getMessage());
	    				
	    			} catch (IOException e) {
	    				Log.w("TAG", "Error saving image file: " + e.getMessage());
	    				
	    			}

	    			return filePath;
	    		}	
	    		

	/*==================================End==================================================*/
private class ImageUploaderTask extends AsyncTask<String, Integer, Void> {
		
		@Override
		protected void onPreExecute(){
			simpleWaitDialog = ProgressDialog.show(Messaging.this, "Wait", "Uploading Image");
		}
		
		@Override
		protected Void doInBackground(String... params) {
			new ImageUploadUtility().uploadSingleImage(params[0],imService.getUsername(),pwd,friend.userKey);
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result){
			//super.onPostExecute(result);
			simpleWaitDialog.dismiss();
			
		}
	}
private void getdatafromlocal()
{
	
	localstoragehandler = new LocalStorageHandler(this);
	dbCursor = localstoragehandler.get(friend.userKey, IMService.USERNAME );
	
	if (dbCursor.getCount() > 0){
	int noOfScorer = 0;
	dbCursor.moveToFirst();
	    while ((!dbCursor.isAfterLast())&&noOfScorer<dbCursor.getCount()) 
	    {
	        noOfScorer++;

			this.appendToMessageHistory(dbCursor.getString(2) , dbCursor.getString(3),dbCursor.getInt(4)!=0 ? true :false,dbCursor.getString(5));
			//boolean str=Boolean.parseBoolean(dbCursor.getString(4));
			String ste=dbCursor.getString(5);
			//Toast.makeText(getApplicationContext(), Boolean.parseBoolean(dbCursor.getString(4)), Toast.LENGTH_LONG).show();
	        dbCursor.moveToNext();
	    }
	}
	localstoragehandler.close();
	
	if (msg != null) 
	{
		String type;
		this.appendToMessageHistory(friend.userKey , msg,true, gettype);
		((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).cancel((friend.userKey+msg).hashCode());
	}
	
	
	
	
	
	}
}
